package com.zline.foodraise.db.dao;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.misc.TransactionManager;
import com.j256.ormlite.stmt.QueryBuilder;
import com.zline.foodraise.constant.Constant;
import com.zline.foodraise.db.DatabaseHelper;
import com.zline.foodraise.entity.City;

import org.androidannotations.annotations.EBean;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

/**
 * Created by heshantao on 15/7/10.
 * 城市dao
 */
@EBean
public class CityDao {
    private static final String LOG_TAG = CityDao.class.getSimpleName();
    //Integer 代表主键类型
    Dao<City, Integer> cityDao;
    DatabaseHelper helper;

    public void setHelper(DatabaseHelper helper) {
        this.helper = helper;
    }

    void getInstance() {
        try {
            if (cityDao == null) {
                cityDao = helper.getDao(City.class);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //添加
    public void add(final City city) {
        try {
            helper.getWritableDatabase();
            getInstance();
            //事务
            TransactionManager.callInTransaction(helper.getConnectionSource(), new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    cityDao.create(city);
                    return null;
                }
            });
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //查询某省下面的地级市
    public List<City> findCityByProvinceId(int provinceId) {
        helper.getReadableDatabase();
        getInstance();
        QueryBuilder queryBuilder = cityDao.queryBuilder();
        List<City> list = new ArrayList<City>();
        try {
            queryBuilder.where().eq(Constant.PROINCE_ID, provinceId);
            list = queryBuilder.query();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    //查询表中所有城市
    public List<City> findAll() {
        helper.getReadableDatabase();
        getInstance();
        List<City> list = new ArrayList<City>();
        try {
            list = cityDao.queryForAll();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }


}
